import { Component } from '@angular/core';
import { HttpService } from 'src/app/service/http.service';
import { ConfigService } from 'src/app/service/config.service';
import { UrlService } from 'src/app/service/url.service';
import { ToolService } from 'src/app/service/tool.service';
import { NavController } from '@ionic/angular';
import { EventService } from 'src/app/service/event.service';
import { Storage } from '@ionic/storage';
import { Router } from '@angular/router';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {
  private clockNum=0;
  public flag;
  public isAnimation=true;
  constructor(private http: HttpService, private navCtrl: NavController, private eventS: EventService,private store:Storage,private router:Router) {
    this.isLogin(3);
    this.initEvent();
  }

  initEvent(){
    let that=this;
    //每次回到首页的时候重置clockNum的值
    this.eventS.subscribe('getClockNum',function(){
      that.clockNum=3;
      that.eventS.publish("indexStartTime");
    },true);
    this.eventS.subscribe('self-tab',function(index){
        that.selectFun(index);
    });
  }

  isLogin(index) {
    let that = this;
    this.http.get(UrlService.USER_TOKEN, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
   //   console.log("返回的token:",ToolService.aesDecodeToJson(data.data),"-code:",data.code);
      if (data.code != ConfigService.LOGIN_CODE) {
        that.store.set(ConfigService.IS_LOGIN_STORE_KEY, "1");
        that.triggerEvent(index);
      } else {
        this.store.remove(ConfigService.IS_LOGIN_STORE_KEY);
        if(index!=3){
          this.navCtrl.navigateForward("/login");
        }
      }
    }, error => {
      console.log("error", error);
    });
  }

  selectFun(index) {
    this.isLogin(index);
    if(index!=3){//清除所有计时器的队列
      this.eventS.publish("indexClearTimeOut");
    }
    if(index==3){//跳转到游戏大厅(盘口详细页面)
      this.isAnimation=true;//css动画启动
       if(!ToolService.isEmpty($("app-root").attr("code")) && !ToolService.isEmpty($("app-root").attr("name"))){
        let param = "{\"code\":\"" + $("app-root").attr("code") + "\",\"name\":\"" + $("app-root").attr("name") + "\",\"lotteryId\":\"" + $("app-root").attr("lotteryId") + "\"}";
        this.router.navigate(['/lotdetail'], {
          queryParams: { "p": ToolService.paramAESEncrypt(param)}
        });
       }else{
         this.navCtrl.navigateRoot("/");
       }
    }
  }
  triggerEvent(index){
    if(this.clockNum!=index){
      this.eventS.publish("selectCommonTab"+index,index);
      this.clockNum=index;
    }
  }


  change(event){
    this.flag=event.detail.tab;
  }

  aniEndFun(){
    this.isAnimation=false;
  }

  // if (ToolService.isEmpty(StorageService.getValue(ConfigService.IS_LOGIN_STORE_KEY))) {
  //   this.navCtrl.navigateForward("/login");
  //   return;
  // }

}
